﻿using lwzlz.Application.System;
using lwzlz.Core;
using lwzlz.Web.Areas.SysAdmin.Models;
using lzwlz.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace lwzlz.Web.Areas.Mall.Controllers
{
    public class ShoppingCartController : MallController
    {
        #region 接口
        /// <summary>
        /// 获取地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetAddress()
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var memberLogin = MallMemberLogin.GetCurrentUser();
                var addressList = new AddressService().GetList(memberLogin.Id);
                response.Data = addressList;
                response.Success = true;
                response.Message = "获取成功";
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 获取购物车
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetShoppingCart()
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var memberLogin = MallMemberLogin.GetCurrentUser();
                var shoppingCartList = new ShoppingCartService().GetList(memberLogin.Id);
                response.Data = shoppingCartList;
                response.Success = true;
                response.Message = "获取成功";
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteShoppingCart(int CommodityId)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var memberLogin = MallMemberLogin.GetCurrentUser();
                var shoppingCartService = new ShoppingCartService();
                var shoppingCart = shoppingCartService.Get(memberLogin.Id, CommodityId);
                if (shoppingCart != null)
                {
                    shoppingCartService.DeleteList(shoppingCart.Id.ToString());
                    response.Success = true;
                    response.Message = "删除成功";
                }
                else
                {
                    throw new Exception("购物车商品错误");
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 调整购物车数量
        /// </summary>
        /// <param name="CommodityId"></param>
        /// <param name="NUmber"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult OperationNumber(int CommodityId, int Type)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var memberLogin = MallMemberLogin.GetCurrentUser();
                var shoppingCartService = new ShoppingCartService();
                var shoppingCart = shoppingCartService.Get(memberLogin.Id, CommodityId);
                if (shoppingCart != null)
                {
                    if (Type == 1)
                    {
                        shoppingCart.Number += 1;
                    }
                    else
                    {
                        shoppingCart.Number -= 1;
                    }
                    var result = shoppingCartService.Update(shoppingCart, null);
                    if (result > 0)
                    {
                        response.Success = true;
                        response.Message = "调整成功";
                    }
                    else
                    {
                        throw new Exception("调整错误");
                    }
                }
                else
                {
                    throw new Exception("购物车商品错误");
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 下单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddOrder(int AddressId, List<string> OrderList)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var memberLogin = MallMemberLogin.GetCurrentUser();
                var shoppingCartService = new ShoppingCartService();
                var shoppingCartList = shoppingCartService.GetList(memberLogin.Id);
                var list = new List<OrderDetail>();
                foreach (var item in OrderList)
                {
                    var itemArr = item.Split('-');
                    var commodityId = int.Parse(itemArr[0]);
                    var number = int.Parse(itemArr[1]);
                    var commodity = new CommodityService().GetCommodity(commodityId);
                    if (commodity != null && !commodity.IsDeleted)
                    {
                        if (!commodity.IsDeleted)
                        {
                            if (commodity.Number >= number)
                            {
                                var orderDetail = new OrderDetail()
                                {
                                    CommodityId = commodityId,
                                    CommodityName = commodity.Name,
                                    CommodityCode = commodity.Code,
                                    CategoryId = commodity.CategoryId,
                                    CategoryName = commodity.CategoryName,
                                    CommodityPic = commodity.Pic,
                                    CommodityIntroduce = commodity.Introduce,
                                    CommodityMoney = commodity.Money,
                                    Number = number,
                                    TotalMoney = commodity.Money * number,
                                    CreationTime = DateTime.Now,
                                    IsDeleted = false
                                };
                                list.Add(orderDetail);
                            }
                            else
                            {
                                throw new Exception(commodity.Name + "商品还剩" + commodity.Number + "件");
                            }
                        }
                        else
                        {
                            throw new Exception(commodity.Name + "商品已下架");
                        }
                    }
                    else
                    {
                        throw new Exception("购物车商品错误");
                    }

                }

                var order = new Order()
                {
                    MemberId = memberLogin.Id,
                    Code = "ORD" + DateTime.Now.ToString("yyyyMMdd") + new Random().Next(0, 99999).ToString("0000"),//Ord202008292151
                    Status = 10,
                    OrderTime = DateTime.Now,
                    TotalAmount = list.Sum(p => p.TotalMoney.Value),
                    CreationTime = DateTime.Now,
                    IsDeleted = false
                };

                var resultOrder = new OrderService().Insert(order, null);
                if (resultOrder.HasValue && resultOrder.Value > 0)
                {
                    var address = new AddressService().Get(AddressId);
                    var orderAddress = new OrderAddress()
                    {
                        OrderId = resultOrder.Value,
                        RealName = address.RealName,
                        Mobile = address.Mobile,
                        ProvinceName = address.ProvinceName,
                        ProvinceCode = address.ProvinceCode,
                        CityName = address.CityName,
                        CityCode = address.CityCode,
                        SendAddress = address.SendAddress,
                        PostCode = address.PostCode,
                        CreationTime = DateTime.Now,
                        IsDeleted = false

                    };
                    var resultOrderAddress = new OrderAddressService().Insert(orderAddress, null);

                    var orderRecord = new OrderRecord()
                    {
                        OrderId = resultOrder.Value,
                        Type = 10,
                        CreationTime = DateTime.Now,
                        IsDeleted = false
                    };
                    var resultOrderRecord = new OrderRecordService().Insert(orderRecord, null);

                    foreach (var item in list)
                    {
                        item.OrderId = resultOrder.Value;
                        var resultOrderDetail = new OrderDetailService().Insert(item, null);

                        var commodity = new CommodityService().Get(item.CommodityId);
                        commodity.Number -= item.Number.Value;
                        var resultCommodity = new CommodityService().Update(commodity, null);

                        var shoppingCart = new ShoppingCartService().Get(memberLogin.Id, item.CommodityId);
                        if (shoppingCart.Number > item.Number)
                        {
                            shoppingCart.Number -= item.Number.Value;
                            var resultShoppingCart = new ShoppingCartService().Update(shoppingCart, null);
                        }
                        else if (shoppingCart.Number == item.Number)
                        {
                            new ShoppingCartService().DeleteList(shoppingCart.Id.ToString());
                        }
                    }
                    response.Data = new { TotalAmount = order.TotalAmount, OrderId = resultOrder.Value };
                    response.Success = true;
                    response.Message = "下单成功";
                }
                else
                {
                    throw new Exception("下单错误");
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ConfirmPay(int OrderId)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                new OrderService().PaySuccessList(OrderId.ToString());
                response.Success = true;
                response.Message = "支付成功";
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response, JsonRequestBehavior.DenyGet);
        }
        #endregion
    }
}